/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * Copyright (c) 2013-2014 jfinal app. jfapp Group.
 */

package app.controllers.admin.wx;

import app.models.wx.Account;
import app.models.DaoKit;
import app.models.wx.Menu;
import app.wxchat.WxChatMessageHelper;
import com.github.sog.controller.AjaxMessage;
import com.github.sog.controller.BasicController;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.jfinal.module.wxchat.api.AccessTokenApi;
import com.jfinal.module.wxchat.api.MenuApi;
import com.jfinal.module.wxchat.api.beans.Button;
import com.jfinal.module.wxchat.api.beans.ErrCodeMsg;
import com.jfinal.module.wxchat.core.Constants;
import com.jfinal.module.wxchat.message.OutputMessage;
import com.jfinal.module.wxchat.message.output.Item;
import com.jfinal.module.wxchat.message.output.NewsOutputMessage;
import com.jfinal.module.wxchat.message.output.TextOutputMessage;
import com.jfinal.module.wxchat.utils.MessageUtil;
import com.jfinal.upload.UploadFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * .
 * </p>
 *
 * @author Jerry Ou
 * @version 1.0 2014-02-12 13:41
 * @since JDK 1.6
 */
public class MenuController extends BasicController {
    private Logger logger = LoggerFactory.getLogger(MenuController.class);

    private void parseMessage(Menu menu) {
        String json = menu.getStr("json");
        try {
            Object id = null;
            OutputMessage message;
            String type = Constants.MSGTYPE_NEWS;
            if (!Strings.isNullOrEmpty(json)) {
                Map<String, String> map = MessageUtil.parseXml(json);
                type = map.get("MsgType");
                Class<? extends OutputMessage> clz = null;
                if (Constants.MSGTYPE_NEWS.equals(type)) {
                    clz = NewsOutputMessage.class;
                } else {
                    clz = TextOutputMessage.class;
                }
                logger.debug(json);
                message = MessageUtil.xmlToOutputMessage(json, clz);
            } else {
                NewsOutputMessage news = new NewsOutputMessage.Builder("", "", 0l, "").build();
                List<Item> items = Lists.newArrayList(new Item("","","",""));
                news.setArticles(items);
                message = news;
            }
            setAttr("id", menu.get("id"));
            setAttr("message_type", type);
            setAttr("message", message);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("parseMessage error, menu is {}", menu);
        }
    }


    public void index() {
        List<Menu> menus = Menu.dao.menus();
        setAttr("menus", menus);
        render("index.ftl");
    }

    public void save() {
        try {
            Menu menu = getModel(Menu.class);
            if (menu.get("parent") == null) {

                Menu top = Menu.dao.findById(Menu.ID);
                if (top == null) {
                    top = new Menu();
                    top.set("id", Menu.ID);
                    top.set("parent", 0);
                    top.set("create_time", new Date());
                    top.save();
                }

                menu.set("parent", top.get("id"));
            }
            if (DaoKit.isNew(menu)) {
                menu.set("create_time", new Date());
                menu.save();
            } else {
                menu.update();
            }
            renderJson(AjaxMessage.ok("保存成功", menu));
        } catch (Exception e) {
            renderJson(AjaxMessage.error("操作失败"));
        }
    }

    public void delete() {
        try {
            long id = getParaToLong("id", -1l);
            Menu.dao.changeStatus(id, false);
            renderJson(AjaxMessage.ok("删除成功"));
        } catch (Exception e) {
            renderJson(AjaxMessage.ok("删除失败"));
        }
    }

    public void create() {
        List<Menu> menus = Menu.dao.menus();
        if (menus != null && !menus.isEmpty()) {
            //Button button = new Button();
            List<com.jfinal.module.wxchat.api.beans.Menu> list = toWxMenus(menus);
            Button button = new Button(list);
            String json = button.toJSONString();

            Menu b = Menu.dao.findById(Menu.ID);
            b.set("json", json);
            b.update();

            System.out.println(json);

            Account account = Account.dao.list().get(0);
            ErrCodeMsg msg = MenuApi.createMenu(json, AccessTokenApi.getAccessToken(account.getStr("appid"), account.getStr("appsecret")).getAccess_token());
            if ("0".equals(msg.getErrcode())) {
                renderJson(AjaxMessage.ok("生成菜单成功"));
            } else {
                renderJson(AjaxMessage.ok("生成菜单失败，响应结果为 : errcode=" + msg.getErrcode() + ", errmsg" + msg.getErrmsg()));
            }
        } else {
            renderJson(AjaxMessage.ok("请先保存菜单"));
        }
    }


    private List<com.jfinal.module.wxchat.api.beans.Menu> toWxMenus(List<Menu> menus) {
        List<com.jfinal.module.wxchat.api.beans.Menu> list = Lists.newArrayList();
        for (Menu menu : menus) {
            com.jfinal.module.wxchat.api.beans.Menu m = new com.jfinal.module.wxchat.api.beans.Menu();
            m.setName(menu.getStr("name"));

            List<Menu> subs = menu.get("subs");
            if (subs != null && !subs.isEmpty()) {
                List<com.jfinal.module.wxchat.api.beans.Menu> sub_button = toWxMenus(subs);
                m.setSub_button(sub_button);
            } else {
                String menu_type = menu.getStr("menu_type");
                m.setType(menu_type);
                if (Constants.EVENT_CLICK.equalsIgnoreCase(menu_type)) {
                    m.setKey(menu.getStr("evt"));
                } else {
                    m.setUrl(menu.getStr("url_path"));
                }
            }

            list.add(m);
        }
        return list;
     }

    public void revoke() {
        Account account = Account.dao.list().get(0);
        ErrCodeMsg msg = MenuApi.deleteMenu(AccessTokenApi.getAccessToken(account.getStr("appid"), account.getStr("appsecret")).getAccess_token());
        if ("0".equals(msg.getErrcode())) {
            renderJson(AjaxMessage.ok("删除菜单成功"));
        } else {
            renderJson(AjaxMessage.ok("删除菜单失败，响应结果为 : errcode=" + msg.getErrcode() + ", errmsg" + msg.getErrmsg()));
        }
    }

    public void message() {
        long id = getParaToLong(0, 0l);
        Menu menu = Menu.dao.findById(id);
        setMessageTip(menu);
        parseMessage(menu);
        render("../message/item.ftl");
    }

    private void setMessageTip(Menu menu) {
        setAttr("_title_", menu.getStr("name") + "回复消息");
        setAttr("keyword", menu.getStr("evt"));
        setAttr("_small_", "设置菜单点击时回复消息信息");
        setAttr("_li2_", menu.getStr("name") + "回复消息");
        setAttr("_head_", menu.getStr("name") + "回复消息");
        setAttr("register", "false");
        setAttr("menu", "true");
    }


    public void messageSave() {

        long id = 0l;
        try {
            List<UploadFile> files = getFiles();

            id = getParaToLong("id", 0l);
            String messageType = getPara("message_type");
            Enumeration<String> paraNames = getParaNames();
            OutputMessage message = new WxChatMessageHelper().convert(messageType, files, paraNames, getRequest());

            String content = MessageUtil.outputMessageToXml(message);

            Menu menu = new Menu();
            menu.set("id", id);
            menu.set("json", content);
            boolean b = menu.update();
            System.out.println(b);
            redirect("/admin/wx/menu");
        } catch (Exception e) {
            e.printStackTrace();
            setAttr("error_message", "保存失败");
            setMessageTip(Menu.dao.findById(id));
            render("../message/item.ftl");
        }
    }
}

